package com.summer.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.summer.service.OssService;
import com.summer.utils.ConstantPropertiesUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Service
public class OssServiceImpl implements OssService {
    @Override
    public String uploadFileAvatar(MultipartFile file) {
        // yourEndpoint填写Bucket所在地域对应的Endpoint。以华东1（杭州）为例，Endpoint填写为https://oss-cn-hangzhou.aliyuncs.com。
        String endpoint = ConstantPropertiesUtils.END_POINT;
// 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
        String accessKeyId = ConstantPropertiesUtils.ACCESS_KEY_ID;
        String accessKeySecret = ConstantPropertiesUtils.ACCESS_KEY_SECRET;
// 填写Bucket名称，例如examplebucket。
        String bucketName = ConstantPropertiesUtils.BUCKET_NAME;

        OSS ossClient = null;
        try {
            // 创建OSSClient实例。
            ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
            InputStream inputStream = file.getInputStream();
//            SimpleDateFormat time = new SimpleDateFormat("yyyyMMddHHmmssZ");
//            String timeStamp = time.format(new Date());
//            String sname = file.getOriginalFilename().substring(0,file.getOriginalFilename().lastIndexOf("."));
//            String fileName = sname+timeStamp+file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")) ;
            String uuid = UUID.randomUUID().toString().replaceAll("-","");
            String fileNameF=file.getOriginalFilename();
            String fileName =  uuid+fileNameF.substring(fileNameF.lastIndexOf("."));
            ossClient.putObject(bucketName,fileName,inputStream);
            String url="https://"+bucketName+"."+endpoint+"/"+fileName;
            return url;
        } catch (OSSException | IOException e){
            e.printStackTrace();
        } finally {
            // 关闭OSSClient。
            ossClient.shutdown();
        }
        return null;
    }
}
